package org.pentaho.di.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.PrintWriter;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Date;
import java.text.SimpleDateFormat;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

import org.pentaho.modules.kettle.sys.job.entity.VJobEntity;
import org.pentaho.modules.kettle.sys.job.service.VJobService;

import org.pentaho.di.core.KettleEnvironment;  
import org.pentaho.di.core.exception.KettleException;  
import org.pentaho.di.core.exception.KettleXMLException;  
import org.pentaho.di.job.Job;  
import org.pentaho.di.job.JobMeta;  
import org.pentaho.di.trans.Trans;  
import org.pentaho.di.trans.TransMeta;  

@Controller
@RequestMapping(value="/JobManagement")
public class JobManagementAction {

    @Autowired
    private VJobService vJobService;

    public static final String RUNSTATUS_RUN = "Running"; 
    public static final String RUNSTATUS_UNEXECUTE = "UnExecute"; 
    public static final String RUNSTATUS_STOP = "Stopped"; 

    public static final String JOB_UPLOAD_DIRECTORY = "upload/job";

    /**
    * <idJob,Job>
    */
    private static Map<String,Job> jobMap = new Hashtable<String,Job>();

    @RequestMapping(value = "/getJobList") 
    public void getTotalJobList(HttpServletRequest request, HttpServletResponse response) 
    throws Exception { 
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        List<VJobEntity> vJobList = vJobService.queryList(null);
        String jsonVJobList = JSON.toJSONString(vJobList,
            SerializerFeature.DisableCircularReferenceDetect);
        out.println("{\"data\":" + jsonVJobList + "}");
    }

    @RequestMapping(value = "/getJobContent")
    public void getJobContent(HttpServletRequest request, HttpServletResponse response) 
    throws Exception {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        Long idJob = Long.parseLong(request.getParameter("idJob"));
        VJobEntity vJob = vJobService.queryObject(idJob);

        String jobTotalPath = request.getSession().getServletContext().getRealPath(vJob.getSharedFile());;
        vJob.setSharedFile(jobTotalPath);
        String jsonVJob = JSON.toJSONString(vJob,
            SerializerFeature.DisableCircularReferenceDetect);
        out.write(jsonVJob);
    }

    @RequestMapping(value = "/deleteJob")
    public void deleteJob(HttpServletRequest request, HttpServletResponse response) 
    throws Exception {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        Long idJob = Long.parseLong(request.getParameter("idJob"));
        vJobService.delete(idJob);
        jobMap.remove(idJob.toString());
        String str = "{\"success\":\"true\",\"message\":\"Delete Successful!\"}";
        out.write(str);
    }

    @RequestMapping(value = "/saveJobInfo")
    public void saveJobInfo(MultipartFile file, HttpServletRequest request, HttpServletResponse response) 
    throws Exception {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();

        VJobEntity vJob = new VJobEntity();
        vJob.setName(request.getParameter("jobname"));
        vJob.setJobVersion(request.getParameter("jobVersion"));
        vJob.setDescription(request.getParameter("jobdescription"));
        Date createdDate = new Date();
        vJob.setCreatedDate(createdDate);

        String path = request.getSession().getServletContext().getRealPath(JOB_UPLOAD_DIRECTORY);  
        String fileName="";
        if(file!=null){
            fileName = file.getOriginalFilename();    
        }
        File dir = new File(path,fileName);

        if(!dir.exists()){  
            dir.mkdirs();  
        }  
        file.transferTo(dir);

        //save vJob
        String jobPath = JOB_UPLOAD_DIRECTORY+ "/" + fileName;
        vJob.setSharedFile(jobPath);
        vJob.setRunStatus(RUNSTATUS_UNEXECUTE);
        vJobService.save(vJob);

        String str = "{\"success\":\"true\",\"message\":\"Create Successful!\"}";
        out.write(str);
    }

    @RequestMapping(value = "/startJob")
    public void startJob(HttpServletRequest request, HttpServletResponse response) 
    throws Exception {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        Long idJob = Long.parseLong(request.getParameter("idJob"));
        VJobEntity vJob = vJobService.queryObject(idJob);

        //run job
        String jobTotalPath = request.getSession().getServletContext().getRealPath(vJob.getSharedFile());
        KettleEnvironment.init();  
        // jobTotalPath Job content + Job Name
        JobMeta jobMeta = new JobMeta(jobTotalPath, null);  
        Job job = new Job(null, jobMeta);
        job.setContainerObjectId(idJob.toString());
        // job.setVariable(paraname, paravalue);  
        job.start();
        //store the job
        jobMap.put(idJob.toString(), job);

        // set runStatus
        vJob.setRunStatus(RUNSTATUS_RUN);
        vJobService.update(vJob);

        String str = "{\"success\":\"true\",\"message\":\"Start Job Successful!\"}";
        out.write(str);
    }

    @RequestMapping(value = "/stopJob")
    public void stopJob(HttpServletRequest request, HttpServletResponse response) 
    throws Exception {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        Long idJob = Long.parseLong(request.getParameter("idJob"));
        VJobEntity vJob = vJobService.queryObject(idJob);

        //stop job
        Job job = jobMap.get(idJob.toString());
        job.stopAll();
    
        // set runStatus
        vJob.setRunStatus(RUNSTATUS_STOP);
        vJobService.update(vJob);

        String str = "{\"success\":\"true\",\"message\":\"Stop Job Successful!\"}";
        out.write(str);
    }
  

}